import type { Directive } from 'vue';
//引入库
import hljs from "highlight.js";
//引入样式
import 'highlight.js/styles/monokai-sublime.css'

/**
 * 自定义指令 - html  高亮
 * @param el
 */
export const highlight: Directive = {
    mounted(el) {
        const blocks = el.querySelectorAll("pre code");
        blocks.forEach((el2: any) => {
            hljs.highlightElement(el2);
        });
    }
}

import userStore from './store/user';

/**
 * 自定义指令 - 角色权限
 * @param el
 */
export const role: Directive = {
    mounted(el, binding) {
        const { value } = binding;
        const roles = userStore.state.roles || []
        if (value && Array.isArray(value) && value.length > 0) {
            if (!roles.includes('Admin')) {
                const hasPermission = value.some((role: string) => roles.includes(role));
                if (!hasPermission) {
                    el.parentNode?.removeChild(el); // 移除无权限的按钮
                }
            }
        } else {
            throw new Error(`需要指定权限，如 v-permitssion="['admin']"`);
        }
    }
}

/**
 * 自定义指令 - 按钮权限
 * @param el
 */
export const permits: Directive = {
    mounted(el, binding) {
        const { value } = binding;
        const permissions = userStore.state.permissions || []
        if (value && Array.isArray(value) && value.length > 0) {
            if (!permissions.includes('**:**:**')) {
                const hasPermission = value.some((permission: string) => permissions.includes(permission));
                if (!hasPermission) {
                    el.parentNode?.removeChild(el); // 移除无权限的按钮
                }
            }
        } else {
            throw new Error(`需要指定权限，如 v-permits="['system:user:add']"`);
        }
    }
}